import { Button, Form, FormInstance, Upload, UploadFile } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import React, { useRef, useState } from "react";
import { RcFile, UploadProps } from "antd/lib/upload";
import useMessage from "@/hooks/useMessage";
import styles from "./index.module.less";
import { uploadFile } from "@/api/modules/common";
import { addPhotoApi, updatePhotoApi } from "@/api/modules/album";
import { DataType } from "../PhotoList";
import { flushSync } from "react-dom";

interface PropsType {
	type?: string;
	photo?: DataType;
	currentAlbum?: number;
	onComfirm?: () => void;
}

const AlbumAdd: React.FC<PropsType> = props => {
	const { type, photo, currentAlbum } = props;

	const { contextHolder, success, error } = useMessage();

	const formRef = useRef<FormInstance | null>(null);

	const [fileList, setFileList] = useState<UploadFile[]>([]);

	const handleUpload = async () => {
		const formData = new FormData();
		fileList.forEach(file => {
			formData.append("file", file as RcFile);
		});
		const res = await uploadFile(formData);
		return res.data;
	};

	const uploadProps: UploadProps = {
		onRemove: file => {
			const index = fileList.indexOf(file);
			const newFileList = fileList.slice();
			newFileList.splice(index, 1);
			setFileList(newFileList);
		},
		beforeUpload: file => {
			flushSync(() => {
				setFileList([...fileList, file]);
			});
			return false;
		},
		fileList,
		multiple: type ? false : true
	};

	const onFinish = async () => {
		try {
			let photo_url, photos;
			if (!currentAlbum) return;
			if (fileList.length > 0) {
				const files = await handleUpload();
				if (type) {
					photo_url = files.images[0].imageUrl;
				} else {
					photos = files.images.map(item => {
						return {
							photo_url: item.imageUrl
						};
					});
				}
			}
			if (type) {
				updatePhotoApi({ id: photo?.id, photo_url: photo_url });
			} else {
				addPhotoApi(currentAlbum, photos as any);
			}
			props.onComfirm && props.onComfirm();
			setFileList([]);
			success("发布成功");
		} catch (err) {
			error("发布失败");
		}
	};

	return (
		<div className={styles.root}>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={{ top: 0 }}
			>
				<Form.Item label="文件" valuePropName="fileList">
					<Upload listType="picture-card" {...uploadProps}>
						{type && fileList.length > 0 ? null : (
							<div>
								<PlusOutlined />
								<div style={{ marginTop: 8 }}>上传文件</div>
							</div>
						)}
					</Upload>
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default AlbumAdd;
